package customer

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/model/customer"
	customerReq "counter-help/admin/server/model/customer/request"
	customerRes "counter-help/admin/server/model/customer/response"
	"fmt"
)

type CusOrderService struct{}

// convertCusOrderToResponse 将 CusOrder 转换为 CusOrderListResponse
func convertCusOrderToResponse(order customer.CusOrder) customerRes.CusOrderListResponse {
	return customerRes.CusOrderListResponse{
		ID:              order.ID,
		Title:           order.Title,
		Status:          order.Status,
		IsFirst:         order.IsFirst,
		BudgetMin:       order.BudgetMin,
		BudgetMax:       order.BudgetMax,
		ExPrice:         order.ExPrice,
		AddPrice:        order.AddPrice,
		RefundPrice:     order.RefundPrice,
		UrgencyDegree:   order.UrgencyDegree,
		Background:      order.Background,
		AnRequire:       order.AnRequire,
		Other:           order.Other,
		Attach:          order.Attach,
		BussSubType:     order.BussSubType,
		BussType:        order.BussType,
		ItemType:        order.ItemType,
		InvolvedField:   order.InvolvedField,
		ResearchPurpose: order.ResearchPurpose,
		ResearchDesign:  order.ResearchDesign,
		DataIsFinish:    order.DataIsFinish,
		DataType:        order.DataType,
		OrderEva:        order.OrderEva,
		OrderUserId:     order.OrderUserId,
		CreatedAt:       order.CreatedAt.Unix(),
		UpdatedAt:       order.UpdatedAt.Unix(),
		BackContent:     order.BackContent,
	}
}

// CreateCusOrder 创建 cusOrder 表记录
// Author [piexlmax](https://github.com/piexlmax)
func (cusOrderService *CusOrderService) CreateCusOrder(cusOrder *customer.CusOrder) (err error) {
	err = global.GVA_DB.Create(cusOrder).Error
	return err
}

// DeleteCusOrder 删除 cusOrder 表记录
// Author [piexlmax](https://github.com/piexlmax)
func (cusOrderService *CusOrderService) DeleteCusOrder(ID string) (err error) {
	err = global.GVA_DB.Delete(&customer.CusOrder{}, "id = ?", ID).Error
	return err
}

// DeleteCusOrderByIds 批量删除 cusOrder 表记录
// Author [piexlmax](https://github.com/piexlmax)
func (cusOrderService *CusOrderService) DeleteCusOrderByIds(IDs []string) (err error) {
	err = global.GVA_DB.Delete(&[]customer.CusOrder{}, "id in ?", IDs).Error
	return err
}

// UpdateCusOrder 更新 cusOrder 表记录
// Author [piexlmax](https://github.com/piexlmax)
func (cusOrderService *CusOrderService) UpdateCusOrder(cusOrder customer.CusOrder) (err error) {
	err = global.GVA_DB.Model(&customer.CusOrder{}).Where("id = ?", cusOrder.ID).Updates(&cusOrder).Error
	return err
}

// GetCusOrderInfoList 分页获取 cusOrder 表记录
// Author [piexlmax](https://github.com/piexlmax)
func (cusOrderService *CusOrderService) GetCusOrderInfoList(info customerReq.CusOrderSearch) (list []customer.CusOrder, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)

	// 创建 db
	db := global.GVA_DB.Model(&customer.CusOrder{})
	var cusOrders []customer.CusOrder

	// 如果有条件搜索，下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}

	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&cusOrders).Error
	return cusOrders, total, err
}

// GetAllCusOrders 获取所有订单记录以及每个订单的接单人数
func (cusOrderService *CusOrderService) GetAllCusOrders() ([]customerRes.CusOrderWithAssignmentCountResponse, error) {
	var orders []customer.CusOrder
	err := global.GVA_DB.Where("status = 3").Find(&orders).Error
	if err != nil {
		return nil, err
	}

	var orderResponses []customerRes.CusOrderWithAssignmentCountResponse
	for _, order := range orders {
		// 查询每个订单的接单人数
		var assignmentCount int64
		err := global.GVA_DB.Model(&customer.CusOrderAssignments{}).
			Where("order_id = ?", order.ID).
			Count(&assignmentCount).Error
		if err != nil {
			return nil, err
		}

		// 构造单独返回结构体
		orderResponse := customerRes.CusOrderWithAssignmentCountResponse{
			Order:           convertCusOrderToResponse(order),
			AssignmentCount: assignmentCount, // 单独返回接单人数
		}

		orderResponses = append(orderResponses, orderResponse)
	}

	return orderResponses, nil
}

// GetOrdersByUserID  根据用户 ID 获取订单列表
func (cusOrderService *CusOrderService) GetOrdersByUserID(userID int) ([]customerRes.CusOrderSimpleResponse, error) {
	var orders []customer.CusOrder
	err := global.GVA_DB.Where("order_user_id = ?", userID).Find(&orders).Error
	if err != nil {
		return nil, err
	}

	var orderResponses []customerRes.CusOrderSimpleResponse
	for _, order := range orders {
		orderResponses = append(orderResponses, convertCusOrderToSimpleResponse(order))
	}

	return orderResponses, nil
}

func convertCusOrderToSimpleResponse(order customer.CusOrder) customerRes.CusOrderSimpleResponse {
	return customerRes.CusOrderSimpleResponse{
		ID:            order.ID,
		Title:         order.Title,
		Status:        order.Status,
		BudgetMin:     order.BudgetMin,
		BudgetMax:     order.BudgetMax,
		Background:    order.Background,
		ExPrice:       order.ExPrice,
		UrgencyDegree: order.UrgencyDegree,
		Attach:        order.Attach,
		BussType:      order.BussType,
		ItemType:      order.ItemType,
		CreatedAt:     order.CreatedAt.Unix(),
		UpdatedAt:     order.UpdatedAt.Unix(),
		BackContent:   order.BackContent,
		IsPaid:        order.IsPaid,
		OrderEva:      order.OrderEva,
	}
}

// GetCusOrderByID 根据订单 ID 获取单个订单
func (s *CusOrderService) GetCusOrderByID(orderID string) (customerRes.CusOrderSimpleResponse, error) {
	var order customer.CusOrder
	err := global.GVA_DB.Where("id = ?", orderID).First(&order).Error
	if err != nil {
		return customerRes.CusOrderSimpleResponse{}, err
	}

	return convertCusOrderToSimpleResponse(order), nil
}

// FilterCusOrderList 根据传入的查询条件筛选 CusOrder
func (s *CusOrderService) FilterCusOrderList(params customerReq.SearchParams) (list []customerRes.CusOrderListResponse, total int64, err error) {
	db := global.GVA_DB.Model(&customer.CusOrder{})

	if params.Title != "" {
		db = db.Where("title LIKE ?", "%"+params.Title+"%")
	}
	if params.BussType != "" && params.BussType != "全部" {
		db = db.Where("buss_type = ?", params.BussType)
	}
	if params.BussSubType != "" {
		db = db.Where("buss_sub_type = ?", params.BussSubType)
	}
	if params.ResearchPurpose != "" {
		db = db.Where("research_purpose = ?", params.ResearchPurpose)
	}
	if params.ResearchDesign != "" {
		db = db.Where("research_design = ?", params.ResearchDesign)
	}

	// Handling the urgency degree
	if params.UrgencyDegree != 888 {
		db = db.Where("urgency_degree = ?", params.UrgencyDegree)
	}
	if params.DataType != "" {
		db = db.Where("data_type = ?", params.DataType)
	}
	if params.ItemType != "" {
		db = db.Where("item_type = ?", params.ItemType)
	}
	if params.BudgetMin != nil {
		db = db.Where("budget_min >= ?", *params.BudgetMin)
	}
	if params.BudgetMax != nil {
		db = db.Where("budget_max <= ?", *params.BudgetMax)
	}

	// Implementing sorting
	if params.SortBy != "" {
		switch params.SortBy {
		case "价格最高":
			db = db.Order("budget_max DESC") // Descending order
		case "价格最低":
			db = db.Order("budget_min ASC") // Ascending order
		case "最新发布":
			db = db.Order("created_at DESC") // Descending order
		default:
			// Optionally handle invalid sort values here
		}
	}

	// Query total records count
	err = db.Debug().Count(&total).Error
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	var orders []customer.CusOrder
	// Query data
	err = db.Find(&orders).Debug().Error
	if err != nil {
		return nil, 0, err
	}

	var orderResponses []customerRes.CusOrderListResponse
	for _, order := range orders {
		orderResponses = append(orderResponses, convertCusOrderToResponse(order))
	}

	return orderResponses, total, nil
}
